<template>
  <div>
    <vol-box :lazy="true" :model.sync="modelBox1" title="设置分销" :height="500" :width="600"
      :padding="15">
      <el-divider content-position="left">商品信息</el-divider>
      <div class="flex">
        <img :src="this.goodpic" v-if="this.goodpic" width="80px" height="80px" />
        <div class="mat">
          <div>商品名称：{{goodname}}</div>
          <div>商品价格：{{goodpirce}}</div>
        </div>
      </div>
      <el-divider content-position="left">佣金设置</el-divider>
      <VolForm :loadKey="true" ref="formFieldsreset" :formFields="formFields1"
        :formRules="formRules1"></VolForm>
      <div slot="footer">
        <Button type="default" :loading="loading" @click="submit('editFormFields')">确认</Button>
        <Button type="default" @click="modelBox1 = false">关闭</Button>
      </div>
    </vol-box>
    <vol-box :model.sync="addModel" title="创建分销商品" :width="950" :height="500">
      <VolForm ref="myform" :loadKey="true" :formFileds="formFileds" :formRules="formRules"
        :labelWidth="100"></VolForm>
      <!-- 表格  -->
      <VolTable :height="340" ref="table" :columns="columns" :ck="false" :index="true"
        :tableData="tableData">
      </VolTable>
      <!-- 添加slot槽覆盖footer的按钮，添加新的按钮 -->
      <div slot="footer">
        <Button type="error" @click="getFirstRow" icon="md-checkmark">保存</Button>
        <Button type="info" @click="addModel= false" icon="md-close">关闭</Button>
      </div>
    </vol-box>
  </div>
</template>

<script>
import VolForm from "@/components/basic/VolForm.vue";
import VolBox from "@/components/basic/VolBox.vue";
import VolTable from "@/components/basic/VolTable.vue";
export default {
  components: { VolForm, VolBox, VolTable },
  data() {
    return {
      modelBox1: false,
      CommissionRules: true,
      ck: false,
      loading: false,
      goodname: "",
      goodpic: "",
      //判断走新增还是编辑
      isXZ: "",
      formFields1: {
        attend: 0,
        commissionRules: 0,
        // achievement: '',
        goodId: "",
        setup: "",
        level: "",
        inpurchase: "",
        settlementmethod: "",
        commissionpay: "",
        gradesystem: [],
        id: "",
        settingtype: "",
        commissionreward: "",
      },
      formRules1: [
        [
          {
            title: "是否参与",
            field: "attend",
            type: "radio",
            data: [
              { key: 0, value: "不参与" },
              { key: 1, value: "参与" },
            ],
            onChange: (val, option) => {
              let settingtype = this.getOption("settingtype");
              let commissionreward = this.getOption("commissionreward");
              if (val == 0) {
                settingtype.hidden = true;
                commissionreward.hidden = true;
              } else {
                settingtype.hidden = false;
                commissionreward.hidden = false;
              }
            },
          },
        ],
        [
          {
            title: "佣金类型",
            field: "settingtype",
            type: "radio",
            data: [
              { key: 0, value: "金额" },
              { key: 1, value: "比例" },
            ],
            onChange: (val, option) => {
              let commissionreward = this.getOption("commissionreward");
              if (val == 0) {
                commissionreward.title = "金额";
              } else {
                commissionreward.title = "比例";
              }
            },
          },
        ],
        [
          {
            title: "金额",
            field: "commissionreward",
            type: "decimal",
            colSize: 6,
          },
        ],
      ],
      JsonData: [],
      goodpirce: "",
      addModel: false,
      formFileds: {
        producttype: [],
        productid: "",
        distributionName: "",
        distributionid: "",
      },
      formRules: [
        [
          {
            title: "分销商",
            required: true,
            field: "distributionName",
            type: "select",
            colSize: 4,
            dataKey: "",
            data: [],
            onChange: (v) => {
              this.formFileds.distributionid = v
              this.formFileds.producttype = []
              this.formFileds.productid = ''
            },
          },
          {
            title: "产品类型",
            required: true,
            field: "producttype",
            type: "cascader",
            dataKey: "tree_protype",
            orginData: [],
            data: [],
            colSize: 4,
            onChange: (v) => {
              let parmas = {
                page: 1,
                rows: 30,
                sort: "createDate",
                order: "desc",
                wheres: `[{"name":"typeCode","value":"${
                  v[v.length - 1]
                }","displayType":"cascader"},{\"name\":\"isdistriProduct\",\"value\":\"1\",\"displayType\":\"NoEqual\"},{\"name\":\"distributionid\",\"value\":\"${
                  this.formFileds.distributionid
                }\",\"displayType\":\"select\"},{\"name\":\"effectiveState\",\"value\":\"0\",\"displayType\":\"select\"}]`,
              };
              let productid = this.getFormOption("productid");
              this.http
                .post("/api/distriProducts/getPageData", parmas)
                .then((res) => {
                  productid.data = res.rows.map((i) => {
                    return {
                      key: i.id,
                      value: i.productName,
                    };
                  });
                });
            },
          },
          {
            title: "产品名称",
            field: "productid",
            type: "select",
            colSize: 4,
            data: [],
            required: true,
            onChange: (v) => {
              let parmas = {
                page: 1,
                rows: 30,
                sort: "id",
                order: "desc",
                wheres: "[]",
                value: v,
              };

              this.http
                .post("/api/distriProducts/getDetailPage", parmas)
                .then((res) => {
                  this.tableData = res.rows;
                });
            },
          },
        ],
      ],
      // 列表数据
      tableData: [],
      columns: [
        {
          field: "spare2",
          title: "商品编码",
          type: "string",
          width: 150,
          align: "left",
          fixed: "left",
        },
        {
          field: "spare1",
          title: "商品名称",
          type: "string",
          width: 150,
          align: "left",
          fixed: "left",
        },
        {
          field: "offlineCode",
          title: "线下编码",
          type: "string",
          require: true,
          width: 150,
          align: "left",
        },
        {
          field: "preferentialPrice",
          title: "优惠价",
          type: "string",
          width: 90,
          align: "left",
        },
      ],
    };
  },
  created() {
    this.http
      .post("/api/Dictionary/GetVueDictionary", ["tree_protype"])
      .then((res) => {
        res[0].data.forEach((i) => {
          i.label = i.value;
        });
        this.formRules.forEach((i) => {
          i.forEach((x) => {
            if (x.field == "producttype") {
              x.data.push(
                ...this.base.convertTree(
                  JSON.parse(JSON.stringify(res[0].data)),
                  (node, data, isRoot) => {
                    node.label = node.value;
                    node.value = node.key;
                  }
                )
              );
              x.orginData.push(...res[0].data);
            }
          });
        });
      });
    this.getMenu();
  },
  methods: {
    openadd() {
      this.addModel = true
      this.tableData = []
      this.$refs.myform.reset()
    },
    getMenu() {
      let params = {
        page: 1,
        rows: 30,
        sort: "createDate",
        order: "desc",
        wheres:
          '[{"name":"distributorType","value":"2006,2004","displayType":"checkbox"}]',
      };
      this.http
        .post("api/DistributorNews/getPageData", params, false)
        .then((reslut) => {
          let vf = this.getFormOption("distributionName");
          vf.data = reslut.rows.map(i => {
            return {
              key: i.distributorCode,
              value: i.distributorName
            }
          })
        });
    },
    getFormOption(field) {
      let option;
      this.formRules.forEach((x) => {
        x.forEach((item) => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    getOption(field) {
      let option;
      this.formRules1.forEach((x) => {
        x.forEach((item) => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    getModel(val) {
      //根据分销商ID获取分销商的详细信息
      this.http
        .get("api/distriProducts/GetDistributors?id=" + val, {}, true)
        .then((reslut) => {
          if (reslut) {
            this.formFileds.status = reslut.data.status;
            this.formFileds.code = reslut.data.distributorCode;
            this.model = true; //打开弹框
          }
        });
    },
    getProductModel(val) {
      //根据产品ID获取产品下所有商品
      this.http
        .get("api/distriProducts/getGoods?id=" + val, {}, true)
        .then((reslut) => {
          this.formFileds.supplierid = reslut.data.disCode;
          reslut.data.goodList.forEach((item) => {
            let dataitem = {};
            dataitem.spare1 = item.name;
            dataitem.spare2 = item.code;
            dataitem.goodid = item.goodId;
            dataitem.sellingPrice = item.originalPrice;
            dataitem.preferentialPrice = item.preferentialPrice;
            dataitem.vipPrice = 0;
            dataitem.settlementPrice = 0;
            dataitem.channelPrice = 0;
            dataitem.offlineCode = item.offlineCode;
            dataitem.isAvailable = 1;
            this.$refs.table.addRow(dataitem);
          });
        });
    },
    // 保存按钮
    getFirstRow() {
      this.$refs.myform.validate(() => {
        if (!this.tableData.length) {
          return this.$Message.error("请选择有商品的产品");
        }
        this.http
          .get(
            "/api/distriProducts/UpdateisDistriProduct?distriprodtctid=" +
              this.formFileds.productid
          )
          .then((res) => {
            if (res.status) {
              this.addModel = false;
              this.$Message.success(res.message);
              this.$store.getters.data().viewPageTest.refresh()
            } else {
              this.$Message.error(res.message);
            }
          });
      });
    },
    open(row) {
      this.goodname = row.goodname;
      this.goodpic = row.goodpic;
      this.formFields1.goodId = row.goodid;
      this.formFields1.id = row.id;
      this.goodpirce = row.goodpirce;
      let params = {
        page: 1,
        rows: 10,
        sort: "id",
        order: "desc",
        wheres: `[{name:"goodId",value:"${this.formFields1.goodId}",displayType:"text"}]`,
      };

      this.http
        .post("api/Mall_good_distributor_system/GetPageGoodSystemData", params)
        .then((res) => {
          this.modelBox1 = true;

          this.isXZ = res.rows;
          console.log(this.isXZ);
          this.formFields1.attend = 0;
          if (this.isXZ.length > 0) {
            this.formFields1.attend = res.rows[0].attend;
            this.formFields1.achievement = res.rows[0].achievement;
            this.formFields1.commissionRules = res.rows[0].commissionRules;
            this.formFields1.level = res.rows[0].level;
            this.formFields1.inpurchase = res.rows[0].inpurchase;
            this.formFields1.settlementmethod = res.rows[0].settlementmethod;
            this.formFields1.commissionpay = res.rows[0].commissionpay;
            this.formFields1.setup = res.rows[0].setup;
            this.formFields1.settingtype = res.rows[0].settingtype;
            this.formFields1.commissionreward = res.rows[0].commissionreward;
          }
          let settingtype = this.getOption("settingtype");
          let commissionreward = this.getOption("commissionreward");
          if (res.rows.length == 0 || res.rows[0].attend == 0) {
            settingtype.hidden = true;
            commissionreward.hidden = true;
          } else {
            settingtype.hidden = false;
            commissionreward.hidden = false;
            if (val == 0) {
              commissionreward.title = "金额";
            } else {
              commissionreward.title = "比例";
            }
          }
        });
    },
    submit() {
      let formData = {
        mainData: this.formFields1,
        detailData: null,
        delKeys: null,
      };
      this.loading = true;
      if (this.isXZ.length == 0) {
        this.http
          .post("api/Mall_good_distributor_system/AddGoodSystemData", formData)
          .then((res) => {
            this.loading = false;
            if (res.status) {
              this.modelBox1 = false;
              this.$Message.success(res.message);
              this.$store.getters.data().viewPageTest.refresh();
            } else {
              this.$Message.error(res.message);
            }
          });
      } else {
        this.http
          .post(
            "api/Mall_good_distributor_system/UpdateGoodSystemData",
            formData
          )
          .then((res) => {
            this.loading = false;
            if (res.status) {
              this.modelBox1 = false;
              this.$Message.success(res.message);
              this.$store.getters.data().viewPageTest.refresh();
            } else {
              this.$Message.error(res.message);
            }
          });
      }
    },
  },
};
</script>

<style>
</style>
<style scoped lang="less">
.spanJZ {
  width: 200px;
  height: 80px;
  /* border: 1px solid red; */
  text-align: center;
  /* display: block; */
  display: inline-block;
  line-height: 80px;
  margin: 0 auto;
}
.flex {
  display: flex;
  .mat {
    margin-left: 20px;
    div {
      margin-bottom: 20px;
    }
  }
}
.el-input-group__append {
  padding: 0px 0px;
}
</style>
<style >
.bigtable .el-input.el-input-group--append {
  width: 70px;
}
.bigtable .el-input__inner {
  width: 40px;
  padding: 0px 0px;
}
.bigtable .el-input-group__append {
  padding: 0px 10px;
}
</style>
